package com.muqi.app.qlearn.ui;

import static nl.qbusict.cupboard.CupboardFactory.cupboard;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.jivesoftware.smackx.receipts.ReceiptReceivedListener;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;

import com.muqi.app.network.http.GlideImageUtils;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.project.utils.TimeMangerUtil;
import com.muqi.app.qlearn.adapter.CommentAdapter;
import com.muqi.app.qlearn.adapter.HomeWkPhotoAdapter;
import com.muqi.app.qlearn.modles.CommentBean;
import com.muqi.app.qlearn.modles.HomeWorkBean;
import com.muqi.app.qlearn.modles.HomeWorkFile;
import com.muqi.app.qlearn.modles.MediaInfo;
import com.muqi.app.qlearn.student.BaseSpeechActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.user.db.CupboardSQLiteOpenHelper;
import com.muqi.app.user.db.TreeLeaf;
import com.muqi.app.user.widget.MyGridView;
import com.muqi.app.widget.pulltorefresh.XListView;
import com.muqi.app.widget.scanpicture.ScanPictureActivity;

public class MyHomeWkDetailsActivity extends BaseSpeechActivity implements
		XListView.IXListViewListener, OnItemClickListener, OnClickListener {
	public static final String HOMEWORK_ID = "homework_id";
	public static final String HOMEWORK_DETAILS = "homework_details";
	public static final String HOMEWORK_CONFIRM_TYPE = "homework_confirm_type";
	public static final String HOMEWORK_CONFIRM_PARENT = "homework_confirm_parent";
	private XListView mListview;
	private EditText contentEdt;

	private ImageView itemAvatar;
	private TextView itemName;
	private TextView itemContent;
	private TextView itemWarning;
	private TextView itemTitle;
	private MyGridView itemPicView;
	private LinearLayout confirmLayout;
	private LinearLayout cfmWithFlower;
	private LinearLayout confirmButton;
	private RadioButton parentBtn;
	private RadioButton childBtn;

	private List<CommentBean> commentlist = new ArrayList<CommentBean>();
	private CommentAdapter mAdapter = null;
	private int page = 1;

	private String homwkId = "";
	private HomeWorkBean homewkInfo = null;
	private List<MediaInfo> photoLists = new ArrayList<MediaInfo>();
	private HomeWkPhotoAdapter photoAdapter = null;
	private boolean isConfirmWithPAndC = false;

	private String reply_user_id = "";

	private CupboardSQLiteOpenHelper dbHelper;
	private SQLiteDatabase sqlDb;

	private boolean isConfirm;
	private boolean isParent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		homwkId = getIntent().getStringExtra(HOMEWORK_ID);
		if (homwkId == null || TextUtils.isEmpty(homwkId)) {
			finish();
		}
		homewkInfo = (HomeWorkBean) getIntent().getSerializableExtra(
				HOMEWORK_DETAILS);
		setContentView(R.layout.aty_homework_details);
	}

	@SuppressLint("InflateParams")
	@Override
	protected void onInit() {

		mListview = (XListView) findViewById(R.id.xListView);
		mListview.setXListViewListener(this);
		mListview.setPullLoadEnable(false);
		mListview.setPullRefreshEnable(false);
		mListview.setOnItemClickListener(this);
		contentEdt = (EditText) findViewById(R.id.contentEditText);

		View headerView = LayoutInflater.from(this).inflate(
				R.layout.header_homework_details, null);

		itemAvatar = (ImageView) headerView.findViewById(R.id.homewk_logo);
		itemName = (TextView) headerView.findViewById(R.id.homewk_name);
		itemContent = (TextView) headerView.findViewById(R.id.homewk_content);
		itemWarning = (TextView) headerView.findViewById(R.id.homewk_warning);
		itemPicView = (MyGridView) headerView.findViewById(R.id.myGridView);
		itemTitle = (TextView) headerView.findViewById(R.id.homewk_title);
		confirmLayout = (LinearLayout) headerView
				.findViewById(R.id.confirmLayout);
		cfmWithFlower = (LinearLayout) headerView
				.findViewById(R.id.confirmWithFlower);
		cfmWithFlower.setOnClickListener(this);
		confirmButton = (LinearLayout) headerView
				.findViewById(R.id.confirmReceived);
		confirmButton.setOnClickListener(this);

		parentBtn = (RadioButton) headerView
				.findViewById(R.id.parentsRadioButton);
		childBtn = (RadioButton) headerView.findViewById(R.id.childRadioButton);
		parentBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked && childBtn.isChecked() && !isConfirmWithPAndC) {
					confirmingHomeworkWithParents();
				}
			}
		});
		childBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked && parentBtn.isChecked() && !isConfirmWithPAndC) {
					confirmingHomeworkWithParents();
				}
			}
		});

		mListview.addHeaderView(headerView);
		mListview.setAdapter(null);
	}

	@Override
	protected void onData() {
		super.onData();
		showLoading();
		if (homewkInfo != null) {
			showHomeworkDetailView(homewkInfo);
		} else {
			loadingHomeWorkDetails();
		}
		loadingDetailComments();
	}

	private void showHomeworkDetailView(final HomeWorkBean workInfo) {
		itemTitle.setText(workInfo.subject_name + "作业");
		itemName.setText(workInfo.nickname + " " + workInfo.create_time);
		itemContent.setText(workInfo.content);
		if (workInfo.warning != null && !"".equals(workInfo.warning)) {
			itemWarning.setVisibility(View.VISIBLE);
			itemWarning.setText(workInfo.warning);
		} else {
			itemWarning.setVisibility(View.GONE);
		}

		GlideImageUtils.setImageLoader(mContext,
				workInfo.subject_fileurl.fileurl_00, itemAvatar,
				R.drawable.icon_homework_logo_02);
		if (workInfo.classJobFiles != null && workInfo.classJobFiles.size() > 0) {
			for (HomeWorkFile file : workInfo.classJobFiles) {
				photoLists.add(file.fileurlInfo);
			}
			photoAdapter = new HomeWkPhotoAdapter(this, photoLists);
			itemPicView.setAdapter(photoAdapter);
			itemPicView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					List<String> bigUrls = new ArrayList<String>();
					for (MediaInfo info : photoLists) {
						bigUrls.add(info.fileurl_03);
					}
					if (bigUrls.size() > 0) {
						Intent intent = new Intent(
								MyHomeWkDetailsActivity.this,
								ScanPictureActivity.class);
						intent.putExtra(ScanPictureActivity.EXTRA_IMAGE_URLS,
								(ArrayList<String>) bigUrls);
						intent.putExtra(ScanPictureActivity.EXTRA_IMAGE_INDEX,
								arg2);
						startActivity(intent);
					}
				}
			});
		}
		if ("n".equals(workInfo.getConfirmState())) {
			confirmLayout.setVisibility(View.VISIBLE);
		}

		if ("y".equals(workInfo.getWithState())) {
			isConfirmWithPAndC = true;
			parentBtn.setChecked(true);
			childBtn.setChecked(true);
		}

	}

	public void onBack(View v) {

		this.finish();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.confirmWithFlower:
			cfmWithFlower.setEnabled(false);
			confirmButton.setEnabled(false);
			confirmingHomework(1);
			break;
		case R.id.confirmReceived:
			cfmWithFlower.setEnabled(false);
			confirmButton.setEnabled(false);
			confirmingHomework(0);
			break;
		default:
			break;
		}
	}

	private void confirmingHomework(final int flowerCount) {
		if (homewkInfo != null) {
			showLoading();
			if (NetWorkUtils.isNetworkAvailable(this)) {
				HashMap<String, Object> sendMap = new HashMap<String, Object>();
				sendMap.put("token", mSpUtil.getToken());
				sendMap.put("student_id", mSpUtil.getCurrentChildId());
				sendMap.put("id", homwkId);
				sendMap.put("give_flower", flowerCount);
				String requestUrl = ParamsUtils.buildParams(
						NetWorkApi.CONFIRM_HOMEWORK_MESSAGE_API, sendMap);
				MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

					@Override
					public void onAsyncCallBack(RESULTCODE resuleCode,
							String request, String result) {
						hideLoading();
						if (resuleCode == RESULTCODE.SUCCESS) {

							homewkInfo.setConfirmState("y");
							if (flowerCount == 1) {
								cfmWithFlower.setEnabled(true);
								homewkInfo.flowercount = (Integer
										.parseInt(homewkInfo.flowercount) + 1)
										+ "";
								showToast("确认并送花成功");
							} else {
								showToast("已确认");
							}
							Intent intent = new Intent();
							intent.putExtra(HOMEWORK_CONFIRM_TYPE, homewkInfo);
							setResult(RESULT_OK, intent);
							confirmLayout.setVisibility(View.GONE);

						}
					}
				});
			} else {
				ShowToast.showShort(this, R.string.net_break);// 提示无网络
			}
		}

	}

	private void setTreeleafView() {
		dbHelper = new CupboardSQLiteOpenHelper(this);
		sqlDb = dbHelper.getWritableDatabase();
		TreeLeaf todayLeaf = cupboard().withDatabase(sqlDb)
				.query(TreeLeaf.class)
				.withSelection("child_id = ?", mSpUtil.getCurrentChildId())
				.get();
		if (todayLeaf == null) {
			todayLeaf = new TreeLeaf();
			todayLeaf.child_id = mSpUtil.getCurrentChildId();
			todayLeaf.leaf_date = TimeMangerUtil.getNowDate();
			todayLeaf.hasShow = false;
			cupboard().withDatabase(sqlDb).put(todayLeaf);
		} else {
			if (!todayLeaf.leaf_date.equals(TimeMangerUtil.getNowDate())) {
				cupboard().withDatabase(sqlDb).delete(TreeLeaf.class,
						"child_id = ?", mSpUtil.getCurrentChildId());
				TreeLeaf nextOne = new TreeLeaf();
				nextOne.child_id = mSpUtil.getCurrentChildId();
				nextOne.leaf_date = TimeMangerUtil.getNowDate();
				nextOne.hasShow = false;
				cupboard().withDatabase(sqlDb).put(nextOne);
			}
		}
	}

	private void confirmingHomeworkWithParents() {
		showLoading();
		setTreeleafView();
		if (homewkInfo != null) {
			if (NetWorkUtils.isNetworkAvailable(this)) {
				HashMap<String, Object> sendMap = new HashMap<String, Object>();
				sendMap.put("token", mSpUtil.getToken());
				sendMap.put("student_id", mSpUtil.getCurrentChildId());
				sendMap.put("id", homwkId);
				String requestUrl = ParamsUtils.buildParams(
						NetWorkApi.CONFIRM_HOMEWORK_WITH_PARENTS_API, sendMap);
				MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

					@Override
					public void onAsyncCallBack(RESULTCODE resuleCode,
							String request, String result) {
						hideLoading();
						if (resuleCode == RESULTCODE.SUCCESS) {
							homewkInfo.setWithState("y");
							Intent intent = new Intent();
							intent.putExtra(HOMEWORK_CONFIRM_TYPE, homewkInfo);
							setResult(RESULT_OK, intent);

							showToast("已确认陪伴孩子完成本次作业，陪伴成长将体现在成长树上");

						}
					}
				});
			} else {
				ShowToast.showShort(this, R.string.net_break);// 提示无网络
			}
		} else {
			showToast("数据解析失败");
		}

	}

	private void loadingHomeWorkDetails() {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("token", mSpUtil.getToken());
			sendMap.put("student_id", mSpUtil.getCurrentChildId());
			sendMap.put("id", homwkId);
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_MY_HOMEWORK_DETAIL_API, sendMap);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					if (resuleCode == RESULTCODE.SUCCESS) {
						homewkInfo = ResponseUtils.getHomeworkDetails(mContext,
								result);
						if (homewkInfo != null)
							showHomeworkDetailView(homewkInfo);
					} else {
						showToast(result);
						Intent intent = new Intent();
						intent.putExtra("isDelete", true);
						setResult(RESULT_OK, intent);
						finish();

					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	private void loadingDetailComments() {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("id", homwkId);
			sendMap.put("type", "class_job");// 'class_job','goods','socially_activity','message'
			sendMap.put("page", page);
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_HOMEWORK_COMMENTLISTS_API, sendMap);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					onLoadView();
					hideLoading();
					if (resuleCode == RESULTCODE.SUCCESS) {
						List<CommentBean> getLists = ResponseUtils
								.getUserComments(mContext, result);
						if (getLists != null && getLists.size() > 0) {
							Log.e("===", getLists.size() + " ");
							if (getLists.size() < 10) {
								mListview.setPullLoadEnable(false);
							} else {
								mListview.setPullLoadEnable(true);

							}
							if (page == 1) {
								commentlist.clear();
								commentlist = getLists;
								if (mAdapter != null)
									mAdapter = null;
								mAdapter = new CommentAdapter(mContext,
										commentlist);
								mAdapter.setHome(true);
								mListview.setAdapter(mAdapter);
							} else {
								for (CommentBean item : getLists) {
									commentlist.add(item);
								}
								mAdapter.notifyDataSetChanged();
							}
						}
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	private void onLoadView() {
		mListview.stopRefresh();
		mListview.stopLoadMore();
		mListview.setRefreshTime("刚刚");
	}

	public void openVoice2Words(View v) {
		startSpeech();
	}

	@Override
	protected void onSpeech2Words(String speechWords) {
		contentEdt.setText(speechWords);
		contentEdt.setSelection(contentEdt.length());
	}

	public void sendMyCreditMsg(View v) {
		String mContent = contentEdt.getText().toString();
		if (TextUtils.isEmpty(mContent)) {
			showToast("评论内容不能为空哦");
		} else {
			publiMyCommentInfo(reply_user_id, mContent);
			contentEdt.setText("");
			contentEdt.setHint("评论...");
			reply_user_id = "";
			dismissSoftKeyboard();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		if (commentlist.get(position - 2).author_userInfo.id.equals(mSpUtil
				.getUserId())) {
			return;
		}
		reply_user_id = commentlist.get(position - 2).author_userInfo.id;
		contentEdt.setHint("回复:"
				+ commentlist.get(position - 2).author_userInfo.name);
		getSoftInput(contentEdt);
	}

	private void publiMyCommentInfo(String replyUser, String content) {
		if (homewkInfo != null) {
			if (NetWorkUtils.isNetworkAvailable(this)) {
				HashMap<String, Object> sendMap = new HashMap<String, Object>();
				sendMap.put("token", mSpUtil.getToken());
				sendMap.put("obj_type", "class_job");
				sendMap.put("obj_id", homwkId);
				sendMap.put("reply_to_user_id", replyUser);
				sendMap.put("rating", 5);
				sendMap.put("content", content);
				String requestUrl = ParamsUtils.buildParams(
						NetWorkApi.ADD_MYCOMMENT_TO_USER_API, sendMap);
				MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

					@Override
					public void onAsyncCallBack(RESULTCODE resuleCode,
							String request, String result) {
						if (resuleCode == RESULTCODE.SUCCESS) {
							homewkInfo.commentcount = (Integer
									.parseInt(homewkInfo.commentcount) + 1)
									+ "";
							Intent intent = new Intent();
							intent.putExtra(HOMEWORK_CONFIRM_TYPE, homewkInfo);
							setResult(RESULT_OK, intent);
							onRefresh();
						}
					}
				});
			} else {
				ShowToast.showShort(this, R.string.net_break);// 提示无网络
			}
		} else {
			showToast("该记录已被删除，无法评论");
		}

	}

	@Override
	public void onRefresh() {
		page = 1;
		loadingDetailComments();
	}

	@Override
	public void onLoadMore() {
		page++;
		loadingDetailComments();
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		Log.e("===", event.getAction()+" action");
		return super.dispatchKeyEvent(event);
	}
}
